package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.umeng.message.PushAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import java.util.Map;
import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.Qqlogin;
import artid.com.arttogo.bean.UserItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.db.DataKeeper;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.utils.Config;
import artid.com.arttogo.utils.Constant;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;

public class LoginActivity extends BaseActivity implements OnClickListener {
    private TextView mLoginBtn, mForget, mRegister;
    private Intent mIntent;
    private Context mContext;
    private EditText phone, passWord;
    private LinearLayout back;
    MySharedPreferences sharedPreferences;
    String pastuserName = "";
    View hide;
    ImageView imageWx, imageQQ;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // UmengUpdateAgent.update(this);
        initView();

        // mShareAPI = UMShareAPI.get(this);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initView() {
        mContext = this;
        imageWx = (ImageView) findViewById(R.id.wxlogin);
        imageWx.setOnClickListener(this);
        imageQQ = (ImageView) findViewById(R.id.qqlogin);
        imageQQ.setOnClickListener(this);
        sharedPreferences = MySharedPreferences
                .getMySharedPreferences(mContext);
        pastuserName = sharedPreferences.getValue("login", "");
        // hide = (View) findViewById(R.id.hide);
        // hide.setOnClickListener(this);
        // hide.setVisibility(View.GONE);
        mLoginBtn = (TextView) findViewById(R.id.login_btn);
        mForget = (TextView) findViewById(R.id.text_forget_pass);
        mRegister = (TextView) findViewById(R.id.text_to_register);

        phone = (EditText) findViewById(R.id.et_login_phone);
        phone.setOnClickListener(this);
        if (!pastuserName.equals("")) {
            phone.setText(pastuserName);
        }
        passWord = (EditText) findViewById(R.id.et_login_password);
        passWord.setOnClickListener(this);
        passWord.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    onClick(mLoginBtn);
                    //处理事件
                }
                return false;
            }
        });
        // back = (LinearLayout) findViewById(R.id.back);
        mLoginBtn.setOnClickListener(this);
        mForget.setOnClickListener(this);
        mRegister.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);
        // back.setOnClickListener(this);
    }

    /**
     * 登录
     */
    private void login() {
        // TODO Auto-generated method stub
        if (TextUtils.isEmpty(phone.getText().toString())) {
            Toast.makeText(mContext, "账号不能为空", Toast.LENGTH_LONG).show();
            return;
        } else if (TextUtils.isEmpty(passWord.getText().toString())) {
            Toast.makeText(mContext, "密码不能为空", Toast.LENGTH_LONG).show();
            return;
        } else if (!NetUtils.isMobileNO(phone.getText().toString())) {
            Toast.makeText(mContext, "手机号格式不正确，请重新输入~", Toast.LENGTH_LONG).show();
            return;
        }
        String umToken =  PushAgent.getInstance(this).getRegistrationId();
        sharedPreferences.setValue("umToken", umToken);
        VolleyBasic.getInstance(LoginActivity.this).post(
                Cache.login,
                VolleyMap.getInstance().Login(phone.getText().toString(),
                        passWord.getText().toString(), umToken
                ),
                UserItem.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        System.out.println(vd.getJson());
                        if (!TextUtils.isEmpty(vd.getMsg())
                                && vd.getCode() == 0) {
                            Config.showTip(mContext, vd.getMsg());
                        }
                        UserItem us = (UserItem) vd.getData();
                        DataKeeper.keepSerializable(mContext, us);
                        AppUtil.setUser();
                        sharedPreferences.setValue("login", phone.getText()
                                .toString());

                        loginHX();
                        finish();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    /**
     * 环信登陆
     */
    private void loginHX() {
        if (!TextUtils.isEmpty(AppUtil.getUser().getUid())) {
            EMClient.getInstance().login(AppUtil.getUser().getUid(),
                    "yjbgp2016", new EMCallBack() {// 回调
                        @Override
                        public void onSuccess() {
                            Activity activity = (Activity) mContext;
                            activity.runOnUiThread(new Runnable() {
                                public void run() {
                                    Log.d("log", "环信:登陆聊天服务器成功！");
                                }
                            });
                        }

                        @Override
                        public void onProgress(int progress, String status) {
                            Log.d("log", "环信:登陆中！");
                        }

                        @Override
                        public void onError(int code, String message) {
                            Log.d("log", "环信:登陆聊天服务器失败！");
                            loginHX();
                        }
                    });
        }
    }

    private UMSocialService mController = UMServiceFactory
            .getUMSocialService("com.umeng.share");

    private void wxlogin(final SHARE_MEDIA platform) {
        mController.doOauthVerify(LoginActivity.this, platform,
                new UMAuthListener() {

                    @Override
                    public void onStart(SHARE_MEDIA platform) {


                    }

                    @Override
                    public void onError(SocializeException e,
                                        SHARE_MEDIA platform) {
                    }

                    @Override
                    public void onComplete(Bundle value, SHARE_MEDIA platform) {
                        String uid = value.getString("uid");
                        if (!TextUtils.isEmpty(uid)) {
                            getUserInfo(platform);
                        } else {
                            Toast.makeText(LoginActivity.this, "授权失败...",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                    }
                });
    }


    String qqheadurl = "";
    String qqname = "";

    /**
     * 获取授权平台的用户信息
     */
    private void getUserInfo(final SHARE_MEDIA platform) {
        mController.getPlatformInfo(LoginActivity.this, platform,
                new UMDataListener() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (info != null) {
                            Log.d("第三方登录info", info.toString());
                            if (platform.equals(SHARE_MEDIA.QQ)) {
                                String strQQtoken = (String) info.get("profile_image_url");
                                strQQtoken = strQQtoken.substring(strQQtoken.indexOf("qqapp/") + 7);
                                strQQtoken = strQQtoken.substring(strQQtoken.indexOf("/") + 1);
                                strQQtoken = strQQtoken.substring(0, strQQtoken.indexOf("/"));
                                qqheadurl = (String) info.get("profile_image_url");
                                qqname = (String) info.get("screen_name");

                                reqThirdLogin(strQQtoken, "0");

//								Toast.makeText(LoginActivity.this, strQQtoken,
//										Toast.LENGTH_SHORT).show();
                            }
                            if (platform.equals(SHARE_MEDIA.WEIXIN)) {
                                String strwxtoken = (String) info.get("unionid");
                                qqheadurl = (String) info.get("headimgurl");
                                qqname = (String) info.get("nickname");
                                reqThirdLogin(strwxtoken, "1");
//								Toast.makeText(LoginActivity.this, strwxtoken,
//										Toast.LENGTH_SHORT).show();
                            }


                        }
                    }
                });
    }

    void reqThirdLogin(final String appsecret, final String type) {
        VolleyBasic.getInstance(LoginActivity.this).post(
                Cache.qqlogin1,
                VolleyMap.getInstance().qqlogin1(appsecret, type),
                Qqlogin.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        if (!TextUtils.isEmpty(vd.getMsg())
                                && vd.getCode() == 0) {
                            Config.showTip(mContext, vd.getMsg());
                        }
                        Qqlogin qq = (Qqlogin) vd.getData();
                        if (qq.getState().equals("1")) {
                            UserItem us = new UserItem();
                            us.setHeadurl(qq.getHeadurl());
                            us.setMobile(qq.getMobile());
                            us.setRealname(qq.getRealname());
                            us.setToken(qq.getToken());
                            us.setUid(qq.getUid());
                            us.setLogin(true);
                            us.setIsQQ(qq.getQq());
                            us.setIsWx(qq.getWeixin());
                            DataKeeper.keepSerializable(mContext, us);
                            AppUtil.setUser();
                            sharedPreferences.setValue("login", phone.getText().toString());
                            loginHX();
                            finish();
                        } else if (qq.getState().equals("0")) {
                            sharedPreferences.setValue("appsecret", appsecret);
                            sharedPreferences.setValue("qqheadurl", qqheadurl);
                            sharedPreferences.setValue("qqname", qqname);
                            Intent intent = new Intent(LoginActivity.this, BDwxActivity.class);
                            intent.putExtra("type", type);
                            startActivity(intent);

                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn:
                login();
                break;

            case R.id.wxlogin:
                UMWXHandler wxhHandler = new UMWXHandler(LoginActivity.this,
                        Constant.WX_APP_ID, Constant.WX_APP_KEY);
                wxhHandler.setRefreshTokenAvailable(false);
                wxhHandler.addToSocialSDK();
                wxlogin(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.qqlogin:

                // 添加QQ支持, 并且设置QQ分享内容的target url
                UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(
                        LoginActivity.this, Constant.TENCENT_APP_KEY,
                        Constant.TENCENT_APP_SECRET);
                qqSsoHandler.addToSocialSDK();
                wxlogin(SHARE_MEDIA.QQ);
                break;
            case R.id.text_forget_pass:
                mIntent = new Intent(mContext, FindPasswordActivity.class);
                startActivity(mIntent);
                break;
            case R.id.text_to_register:
                mIntent = new Intent(mContext, RegisterActivity.class);
                startActivity(mIntent);
                break;
            case R.id.back:
                AppUtil.Logout(mContext);
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Login Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
